package com.ruoyi.safe.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.CommonCheckType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.safe.mapper.CommonCheckTypeMapper;
import com.ruoyi.safe.service.ICommonCheckTypeService;

/**
 * 检查类型Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-11-16
 */
@Service
public class CommonCheckTypeServiceImpl implements ICommonCheckTypeService 
{
    @Autowired
    private CommonCheckTypeMapper commonCheckTypeMapper;

    /**
     * 查询检查类型
     * 
     * @param id 检查类型主键
     * @return 检查类型
     */
    @Override
    public CommonCheckType selectCommonCheckTypeById(Long id)
    {
        return commonCheckTypeMapper.selectCommonCheckTypeById(id);
    }

    /**
     * 查询检查类型列表
     * 
     * @param commonCheckType 检查类型
     * @return 检查类型
     */
    @Override
    public List<CommonCheckType> selectCommonCheckTypeList(CommonCheckType commonCheckType)
    {
        return commonCheckTypeMapper.selectCommonCheckTypeList(commonCheckType);
    }

    /**
     * 新增检查类型
     * 
     * @param commonCheckType 检查类型
     * @return 结果
     */
    @Override
    public int insertCommonCheckType(CommonCheckType commonCheckType)
    {
        int i = commonCheckTypeMapper.selectCheckTypeCount(commonCheckType.getCheckTypeNo(), commonCheckType.getId());
        if(i > 0){
            throw  new RuntimeException("该类型编号已存在");
        }
        if(commonCheckType.getParentId() == 0){
            commonCheckType.setAncestors(commonCheckType.getCheckTypeNo());
        }else{
            CommonCheckType commonCheckType1 = commonCheckTypeMapper.selectListTypeByTypeNo(commonCheckType.getParentId());
            commonCheckType.setAncestors(commonCheckType1.getAncestors() + ","+commonCheckType.getCheckTypeNo());
        }
        commonCheckType.setCreateTime(DateUtils.getNowDate());
        commonCheckType.setCreateBy(SecurityUtils.getUsername());
        return commonCheckTypeMapper.insertCommonCheckType(commonCheckType);
    }

    /**
     * 修改检查类型
     * 
     * @param commonCheckType 检查类型
     * @return 结果
     */
    @Override
    public int updateCommonCheckType(CommonCheckType commonCheckType)
    {
        int i = commonCheckTypeMapper.selectCheckTypeCount(commonCheckType.getCheckTypeNo(), commonCheckType.getId());
        if(i > 0){
            throw  new RuntimeException("该类型编号已存在");
        }
        if(commonCheckType.getParentId() == 0){
            commonCheckType.setAncestors(commonCheckType.getCheckTypeNo());
        }else{
            CommonCheckType commonCheckType1 = commonCheckTypeMapper.selectListTypeByTypeNo(commonCheckType.getParentId());
            commonCheckType.setAncestors(commonCheckType1.getAncestors() + ","+commonCheckType.getCheckTypeNo());
        }
        commonCheckType.setUpdateTime(DateUtils.getNowDate());
        commonCheckType.setUpdateBy(SecurityUtils.getUsername());
        return commonCheckTypeMapper.updateCommonCheckType(commonCheckType);
    }

    /**
     * 批量删除检查类型
     * 
     * @param ids 需要删除的检查类型主键
     * @return 结果
     */
    @Override
    public int deleteCommonCheckTypeByIds(Long[] ids)
    {
        return commonCheckTypeMapper.deleteCommonCheckTypeByIds(ids);
    }

    /**
     * 删除检查类型信息
     * 
     * @param id 检查类型主键
     * @return 结果
     */
    @Override
    public int deleteCommonCheckTypeById(Long id)
    {
        return commonCheckTypeMapper.deleteCommonCheckTypeById(id);
    }

    @Override
    public List<TreeSelect> buildCheckTypeTreeSelect(List<CommonCheckType> commonCheckTypes) {
        List<CommonCheckType> typeTrees = buildTypeTree(commonCheckTypes);
        return typeTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }
    /**
     * 构建前端所需要树结构
     *
     * @param  commonCheckTypes 类型列表
     * @return 树结构列表
     */
    @Override
    public List<CommonCheckType> buildTypeTree(List<CommonCheckType> commonCheckTypes) {
        List<CommonCheckType> returnList = new ArrayList<CommonCheckType>();
        List<String> tempList = commonCheckTypes.stream().map(CommonCheckType::getCheckTypeNo).collect(Collectors.toList());
        for (CommonCheckType archivesType : commonCheckTypes) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(String.valueOf(archivesType.getParentId()))) {
                recursionFn(commonCheckTypes, archivesType);
                returnList.add(archivesType);
            }
        }
        if (returnList.isEmpty()) {
            returnList = commonCheckTypes;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<CommonCheckType> list, CommonCheckType t) {
        // 得到子节点列表
        List<CommonCheckType> childList = getChildList(list, t);
        t.setChildren(childList);
        for (CommonCheckType tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<CommonCheckType> getChildList(List<CommonCheckType> list, CommonCheckType t) {
        List<CommonCheckType> tlist = new ArrayList<CommonCheckType>();
        Iterator<CommonCheckType> it = list.iterator();
        while (it.hasNext()) {
            CommonCheckType n = (CommonCheckType) it.next();
            if (StringUtils.isNotNull(n.getParentId())) {
                if (String.valueOf(n.getParentId()).equals(t.getCheckTypeNo())) {
                    tlist.add(n);
                }
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<CommonCheckType> list, CommonCheckType t) {
        return getChildList(list, t).size() > 0;
    }

    @Override
    public Set<String> getParentsRegion(List<CommonCheckType> commonCheckTypes, CommonCheckType commonCheckType) {
        Set<String> parentRegionIds = new HashSet<>();

        // Base case: If the current checkType has no parent, return an empty set
        if (commonCheckType.getParentId() == 0) {
            return parentRegionIds;
        }

        // Find the parent checkType in the list
        CommonCheckType parentCheckType = findCheckTypeById(commonCheckTypes, commonCheckType.getParentId().toString());

        // If the parent checkType is found, add its ID to the set
        if (parentCheckType != null) {
            parentRegionIds.add(parentCheckType.getCheckTypeNo());

            // Recursively call the method for the parent checkType
            parentRegionIds.addAll(getParentsRegion(commonCheckTypes, parentCheckType));
        }

        return parentRegionIds;
    }

    @Override
    public List<CommonCheckType> selectCommonCheckTypeListByParentId() {
        return commonCheckTypeMapper.selectCommonCheckTypeByParentId();
    }

    // Helper method to find a CommonCheckType by its ID in the list
    private CommonCheckType findCheckTypeById(List<CommonCheckType> commonCheckTypes, String id) {
        for (CommonCheckType checkType : commonCheckTypes) {
            if (checkType.getCheckTypeNo().equals(id)) {
                return checkType;
            }
        }
        return null;
    }


}
